<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/examine/msgBg.png" mode="widthFix"></image>
		</view>
		<cusHeaderVue titleContent="消息中心" :showBack="false"></cusHeaderVue>

		<view class="tabBox" :style="{ paddingTop: `calc(${scrollerHeight} + 90rpx)` }">
			<view class="tabLi" :class="tabIndex === 0 ? 'tabLiA' : ''" @click="chooseTab(0)">
				OA审批
				<view v-if="badgeCounts.l1 > 0" class="tabBadge">{{ badgeCounts.l1 }}</view>
			</view>
			<view class="tabLi" :class="tabIndex === 1 ? 'tabLiA' : ''" @click="chooseTab(1)">
				预警
				<view v-if="badgeCounts.l2 > 0" class="tabBadge">{{ badgeCounts.l2 }}</view>
			</view>
			<view class="tabLi" :class="tabIndex === 2 ? 'tabLiA' : ''" @click="chooseTab(2)">
				通知
				<view v-if="badgeCounts.l3 > 0" class="tabBadge">{{ badgeCounts.l3 }}</view>
			</view>
		</view>

		<!-- 搜索框在所有标签页都显示 -->
		<view class="inptBox">
			<image src="/static/home/searchIcon.png" mode="widthFix"></image>
			<input v-model="keywords" type="text" placeholder="请输入关键字搜索" placeholder-style="color: #BBC0CB;"
				@confirm="handleSearch" />
		</view>

		<scroll-view scroll-y="true" :refresher-enabled="true" :refresher-triggered="refreshing"
			@refresherrefresh="onRefresherRefresh"
			:style="{ height: `calc(100vh - ${scrollerHeight} - 90rpx - 195rpx)` }" @scrolltolower="onReachBottom">
			<view class="scrollBox">
				<!-- 统一显示所有类型的消息，根据接口返回的数据渲染 -->
				<view>
					<view @click="toMessageDetail(item)" v-for="(item, index) in zhanXinList" :key="item.id || index"
						class="boxLi">
						<view class="boxTop">
							<view class="boxTopLeft">
								<view v-if="!item.readStatus" class="unreadDot"></view>
								<view class="boxName">{{ item.templateContent || item.title || '系统通知' }}</view>
							</view>
							<u-icon name="arrow-right" color="#b7b6c3" size="15"></u-icon>
						</view>
						<!-- 渲染 templateParams：非时间类在上，开始/结束时间在下 -->
						<template v-if="item.templateParams">
							<view class="boxTip" v-for="([key, value], idx) in mainParams(item)" :key="'main-'+key">
								{{ key }}：{{ value }}
							</view>
							<view class="boxTip" v-for="([key, value], idx) in timeParams(item)" :key="'time-'+key">
								{{ key }}：{{ value }}
							</view>
						</template>
						<!-- 条件展示：当处于 OA 审批(tabIndex==0) 且参数值包含“已通过”时显示右侧图标 -->
						<view class="boxStatus" v-if="tabIndex === 0 && hasApproved(item.templateParams)">
							<image src="/static/message/ytg.png" mode="widthFix"></image>
						</view>
						<view class="boxStatus" v-if="tabIndex === 0 && hasApproved1(item.templateParams)">
							<image src="/static/icon/weitongguo.png" mode="widthFix"></image>
						</view>
					</view>
					<view v-if="zhanXinList.length === 0 && !loading" class="no-data">暂无消息</view>
					<view v-if="loading && zhanXinList.length === 0" class="loading-tip">加载中...</view>
				</view>
			</view>

			<!-- 上拉加载提示 -->
			<view v-if="hasMore && zhanXinList.length > 0" class="load-more">加载更多...</view>
			<view v-else-if="!hasMore && zhanXinList.length > 0" class="load-more">没有更多了</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'; // ✅ 删除 onPullDownRefresh
	import cusHeaderVue from '@/components/cus-header.vue';
	import {
		getZhanXinForPage,
		putUpdateSetRead,
		GETNotifyMyWdNum
	} from '@/api/interface.js';
	import {
		requestSubscribe,
		SUBSCRIBE_TYPES,
		promptUserToSubscribe
	} from '@/utils/subscribeMessage.js';

	// 状态
	const scrollerHeight = ref('');
	const tabIndex = ref(0); // 默认显示第一个tab：OA审批
	const keywords = ref('');
	const zhanXinList = ref([]);
	// 未读数字：l1->OA审批；l2->预警；l3->通知
	const badgeCounts = ref({ l1: 0, l2: 0, l3: 0 });

	// 分页
	const pageNo = ref(1);
	const pageSize = ref(10);
	const hasMore = ref(true);
	const loading = ref(false);
	const refreshing = ref(false);

	// 获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: (res) => {
				scrollerHeight.value = res.statusBarHeight + 'px';
			}
		});
	};

	const formatDate = (timestamp) => {
		if (!timestamp && timestamp !== 0) return '';
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	};

	const toMessageDetail = (item) => {
		// 点击时设为已读，并先本地更新，提升交互体验
		if (!item.readStatus) {
			item.readStatus = true;
			putUpdateSetRead({ id: item.id }).catch(() => { /* 接口异常不阻塞跳转 */ })
			// 读取状态变化后刷新徽标数量
			loadTabBadgeCounts();
		}

		if (tabIndex.value === 0) {
			uni.navigateTo({ url: '/pages/examine/examineXq?processInstanceId=' + item.linkId });
		} else {
			uni.setStorageSync('messageItem', item);
			uni.navigateTo({ url: `/pages/message/messageXq?id=${item.id}` });
		}
	};

	// 判断 templateParams 是否包含“已通过”
	const hasApproved = (params) => {
		if (!params) return false;
		try {
			return Object.values(params).some(v => String(v).includes('已通过'));
		} catch (e) { return false; }
	};

		// 判断 templateParams 是否包含“已通过”
	const hasApproved1= (params) => {
		if (!params) return false;
		try {
			return Object.values(params).some(v => String(v).includes('未通过'));
		} catch (e) { return false; }
	};

	// 提取主参数（排除开始/结束时间）
	const mainParams = (item) => {
		const p = (item && item.templateParams) || {};
		const entries = Object.entries(p);
		return entries.filter(([k]) => !/(开始时间|结束时间)/.test(String(k)));
	};
	// 提取时间参数（开始/结束，按固定顺序）
	const timeParams = (item) => {
		const p = (item && item.templateParams) || {};
		const entries = Object.entries(p).filter(([k]) => /(开始时间|结束时间)/.test(String(k)));
		const order = { '开始时间': 1, '结束时间': 2 };
		return entries.sort((a,b) => (order[a[0]]||99) - (order[b[0]]||99));
	};

	// 获取未读徽标数量
	const loadTabBadgeCounts = async () => {
		try {
			const res = await GETNotifyMyWdNum();
			if (res && res.code === 0 && res.data) {
				const d = res.data || {};
				badgeCounts.value = {
					l1: Number(d.l1) || 0,
					l2: Number(d.l2) || 0,
					l3: Number(d.l3) || 0
				};
			}
		} catch (err) {
			console.error('获取未读数量失败', err);
		}
	};

	// 加载通知数据（真实接口）
	const loadNotificationData = async () => {
		if (!hasMore.value && pageNo.value > 1) return;
		if (loading.value) return;

		loading.value = true;
		try {
			
			const statusMap = ['1', '2', '3'];
			const status = statusMap[tabIndex.value];
			const requestParams = { pageNo: pageNo.value, pageSize: pageSize.value, status };
			if (keywords.value.trim()) { requestParams.searchName = keywords.value.trim(); }
			const res = await getZhanXinForPage(requestParams);
			let list = [];
			if (res && res.code === 0) {
				if (res.data === true) list = []; else if (res.data && res.data.list) list = res.data.list;
			}
			if (pageNo.value === 1) zhanXinList.value = list; else zhanXinList.value = [...zhanXinList.value, ...list];
			hasMore.value = list.length >= pageSize.value;
		} catch (err) {
			console.error('加载通知失败', err);
			uni.showToast({ title: '加载失败', icon: 'none' });
		} finally {
			loading.value = false;
			refreshing.value = false;
		}
	};

	const loadData = () => { loadNotificationData(); };

	const chooseTab = (num) => {
		if (tabIndex.value === num) return;
		tabIndex.value = num;
		keywords.value = '';
		pageNo.value = 1;
		hasMore.value = true;
		zhanXinList.value = [];
		loading.value = false;
		loadData();
	};

	const handleSearch = () => {
		pageNo.value = 1;
		hasMore.value = true;
		loadData();
	}

	const onReachBottom = () => {
		if (hasMore.value && !loading.value) {
			pageNo.value++;
			loadData();
		}
	};

	const toUrl = (urlSrc) => { uni.navigateTo({ url: urlSrc }); };

	onLoad(() => { getBarHeight(); loadData(); loadTabBadgeCounts(); });

	// 返回页面时刷新，确保已读状态同步
	onShow(() => {
		pageNo.value = 1;
		hasMore.value = true;
		loadData();
		loadTabBadgeCounts();
	});

	onMounted(() => { console.log('消息页面已加载'); });

	const onRefresherRefresh = () => {
		console.log('下拉刷新触发了！');
		refreshing.value = true;
		pageNo.value = 1; hasMore.value = true;
		zhanXinList.value = [];
		loadData();
		loadTabBadgeCounts();
	};
</script>

<style lang="scss" scoped>
	.content { width: 100%; height: 100vh; position: relative; }

	.bgColor { width: 100%; height: 740rpx; position: absolute; z-index: -1; top: 0;
		image { width: 100%; height: 100%; }
	}

	/* 参数容器样式 */
	.params-container { margin: 8px 0; padding: 8px 10px; background-color: #f5f7fa; border-radius: 4px; }
	.param-item { font-size: 14px; color: #666; line-height: 1.6; }

	.tabBox { display: flex; align-items: center; justify-content: space-around; height: 50rpx;
		.tabLi { font-size: 29.49rpx; font-weight: 400; color: #3f3f3f; position: relative; }
		.tabLiA { font-weight: 500; font-size: 29.49rpx; color: #000000; }
		.tabLiA::after { content: ''; position: absolute; left: 50%; transform: translateX(-50%); bottom: -10rpx; width: 61.54rpx; height: 6.41rpx; border-radius: 3.21rpx; background: linear-gradient(-90deg, #feaf38, #f98434); }
		.tabBadge { position: absolute; top: -10rpx; right: -40rpx; min-width: 30rpx; height: 30rpx; padding: 0 10rpx; border-radius: 15rpx; background: #FF4D4F; color: #ffffff; font-size: 22rpx; line-height: 30rpx; text-align: center; box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.08); }
	}

	.inptBox { width: 705rpx; height: 70rpx; border-radius: 35.26rpx; background: #ffffff; box-shadow: 0.64rpx 1.28rpx 13.46rpx 0 #e19a2e29; margin: 45rpx auto 0; display: flex; align-items: center; padding: 0 27rpx; box-sizing: border-box; margin-bottom: 19rpx;
		image { width: 30.13rpx; height: 30.13rpx; }
		input { flex: 1; font-weight: 400; font-size: 28.21rpx; margin-left: 12rpx; }
	}

	.scrollBox { padding-bottom: 30rpx;
		.boxLi { width: 705rpx; border-radius: 12.82rpx; background: #ffffff; margin: 0 auto 22rpx; padding: 37rpx 27rpx; box-sizing: border-box; position: relative;
			.boxStatus { width: 128rpx; height: 128rpx; position: absolute; top: 137rpx; right: 35rpx;
				image { width: 100%; height: 100%; }
			}
			.boxTop { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14rpx;
				.boxTopLeft { display: flex; align-items: center; flex: 1; min-width: 0; }
				.unreadDot { width: 16rpx; height: 16rpx; border-radius: 50%; background-color: #FF4D4F; margin-right: 10rpx; }
				.boxName { flex: 1; min-width: 0; font-weight: 500; font-size: 33.33rpx; color: #1c2027; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
			}
			.boxTip { color: #5a5964; font-weight: 400; font-size: 25.64rpx; line-height: 48.72rpx; }
		}
	}
	.no-data { text-align: center; color: #868686; padding: 30rpx 0; }
	.loading-tip { text-align: center; color: #868686; padding: 20rpx 0; }
	.load-more { text-align: center; color: #999; padding: 20rpx 0; }
</style>